package com.etlmaster.rowprocessor.steps;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;

import javax.script.ScriptException;

import org.apache.commons.vfs2.FileSystemException;
import com.etlmaster.executor.processors.File.FileTransInfo;
import com.etlmaster.executor.trans.core.Line;
import com.etlmaster.rowprocessor.core.AbstractWriter;
import com.etlmaster.rowprocessor.core.EtlMasterRowProcessException;
import com.etlmaster.rowprocessor.utils.FileWriterUtil;

/**
 * @author Larry
 * @copyright Larry@etlMaster
 * @since 2017-09-10
 */
public class FileWriter extends AbstractWriter {
	long transSize = 0;
	private String targetVfsURI;

	private String targetCharSet;
	private String seprator;

	private long fileMergeSize;
	private FileWriterUtil filewriter;

	public FileWriter(String id, String jobId, String name, String code,
			Map<String, Object> paramMap, Map<String, Object> var) {
		super(id, jobId, name, code, paramMap, var);
	}

	@Override
	public void read(Line line) {
		try {
			filewriter.writeFileByLine(line.toString(getSeprator()));
		} catch (IOException e) {
			e.printStackTrace();
		} catch (ScriptException e) {
			e.printStackTrace();
		}

	}

	@Override
	protected void init() {
		try {
			FileTransInfo transInfo = new FileTransInfo("", getTargetVfsURI());
			transInfo.setSplitType("size");
			transInfo.setSplitSize(fileMergeSize);
			transInfo.setTargetCharSet(targetCharSet);

			filewriter = new FileWriterUtil(transInfo);
			filewriter.setUpTargetObjects(getTargetVfsURI());
		} catch (FileSystemException e) {
						e.printStackTrace();
			throw new EtlMasterRowProcessException();
		} catch (UnsupportedEncodingException e) {
						e.printStackTrace();
			throw new EtlMasterRowProcessException();
		}
	}

	public String getTargetVfsURI() {
		return variableSubstution(targetVfsURI);
	}

	public void setTargetVfsURI(String targetVfsURI) {
		this.targetVfsURI = targetVfsURI;
	}

	public String getTargetCharSet() {
		return variableSubstution(targetCharSet);
	}

	public void setTargetCharSet(String targetCharSet) {
		this.targetCharSet = targetCharSet;
	}

	public long getFileMergeSize() {
		return fileMergeSize * 1024 * 1024;
	}

	public void setFileMergeSize(long fileMergeSize) {
		this.fileMergeSize = fileMergeSize;
	}

	public String getSeprator() {
		return variableSubstution(seprator);
	}

	public void setSeprator(String seprator) {
		this.seprator = seprator;
	}

	@Override
	protected void stop() {
		filewriter.close();
	}

}
